﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QT.Windows.Shell;

namespace UrlChecker.Setting
{
    public partial class SearchEngine : GlassForm
    {
        #region SearchEngine

        public SearchEngine()
        {
            InitializeComponent();
            this.tsslMsg.Text = "新增模式";
        }

        private void SearchEngine_Shown(object sender, EventArgs e)
        {
            InitComboBox();
            LoadData();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            this.statusStrip1.BackColor = AeroColor;
        }

        #endregion

        #region Event

        #region GlassButton

        private void gbtnSave_Click(object sender, EventArgs e)
        {
            if (this.tbName.Text.Length == 0)
            {
                MessageBox.Show("请输入搜索引擎名称");
                return;
            }
            if (this.tbUrl.Text.Length == 0)
            {
                MessageBox.Show("请输入url地址格式");
                return;
            }
            if (this.tbResultRegex.Text.Length == 0)
            {
                MessageBox.Show("请输入搜索结果采集正则表达式");
                return;
            } if (this.tbSectionRegex.Text.Length == 0)
            {
                MessageBox.Show("请输入分段采集正则表达式");
                return;
            }
            if (this.tbHtmlRegex.Text.Length == 0)
            {
                MessageBox.Show("请输入页面信息采集正则表达式");
                return;
            }
            if (this.tbSnapRegex.Text.Length == 0)
            {
                MessageBox.Show("请输入快照信息采集正则表达式");
                return;
            }
            if (this.tbPageRegex.Text.Length == 0)
            {
                MessageBox.Show("请输入页码采集正则表达式");
                return;
            }
            if (this.tbCountRegex.Text.Length == 0)
            {
                MessageBox.Show("请输入收录量采集正则表达式");
                return;
            }
            if (this.lblCodePage.Text.Length == 0 && this.lblCodePage.Text != this.cbbCodeName.SelectedValue.ToString())
            {
                MessageBox.Show("网页编码异常");
                return;
            }

            try
            {
                int rval = 0;
                if (this.gbtnSave.Tag == null || string.IsNullOrEmpty(this.gbtnSave.Tag.ToString())) rval = QT.SEO.SearchEngine.Add(this.tbName.Text, this.tbUrl.Text, this.tbResultRegex.Text, this.tbSectionRegex.Text, this.tbHtmlRegex.Text, this.tbSnapRegex.Text, this.cbbCodeName.SelectedValue.ToString(), this.cbbCodeName.GetItemText(this.cbbCodeName.SelectedItem), this.tbPageRegex.Text,this.tbCountRegex.Text);
                else rval = QT.SEO.SearchEngine.Update(this.gbtnSave.Tag.ToString(), this.tbName.Text, this.tbUrl.Text, this.tbResultRegex.Text, this.tbSectionRegex.Text, this.tbHtmlRegex.Text, this.tbSnapRegex.Text, this.cbbCodeName.SelectedValue.ToString(), this.cbbCodeName.GetItemText(this.cbbCodeName.SelectedItem), this.tbPageRegex.Text,this.tbCountRegex.Text);
                if (rval == -2)
                {
                    MessageBox.Show("搜索引擎名称已存在");
                    return;
                }
                if (rval > 0)
                {
                    LoadData();
                    MessageBox.Show("操作成功");
                }
                else MessageBox.Show("操作失败");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void gbtnClear_Click(object sender, EventArgs e)
        {
            this.tbName.Text = "";
            this.cbbCodeName.SelectedIndex = 0;
            this.tbUrl.Text = "";
            this.tbResultRegex.Text = "";
            this.tbSectionRegex.Text = "";
            this.tbHtmlRegex.Text = "";
            this.tbSnapRegex.Text = "";
            this.tbPageRegex.Text = "";
            this.gbtnSave.Tag = "";
            this.tsslMsg.Text = "新增模式";
        }

        #endregion

        #region ListView

        private void lvResult_SelectedIndexChanged(object sender, EventArgs e)
        {
            toolStripMenuItem_Modify_Click(sender, e);
        }

        #endregion

        #region ComboBox

        private void cbbCodeName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbbCodeName.SelectedValue != null)
            {
                this.lblCodePage.Text = this.cbbCodeName.SelectedValue.ToString();
            }
            else
            {
                this.lblCodePage.Text = "";
            }
        }

        #endregion

        #region ToolStripMenuItem

        private void toolStripMenuItem_Delete_Click(object sender, EventArgs e)
        {
            if (this.lvResult.SelectedItems.Count > 0 && MessageBox.Show("删除后不能恢复，确定要删除吗？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                if (QT.SEO.SearchEngine.Delete(this.lvResult.SelectedItems[0].Tag.ToString()) > 0)
                {
                    MessageBox.Show("操作成功");
                    LoadData();
                }
                else
                {
                    MessageBox.Show("操作失败");
                }
            }
        }

        private void toolStripMenuItem_Modify_Click(object sender, EventArgs e)
        {
            if (this.lvResult.SelectedItems.Count == 1)
            {
                this.tbName.Text = this.lvResult.SelectedItems[0].SubItems[1].Text;
                this.tbUrl.Text = this.lvResult.SelectedItems[0].SubItems[2].Text;
                this.cbbCodeName.SelectedValue = this.lvResult.SelectedItems[0].SubItems[3].Text;
                this.tbResultRegex.Text = this.lvResult.SelectedItems[0].SubItems[5].Text;
                this.tbSectionRegex.Text = this.lvResult.SelectedItems[0].SubItems[6].Text;
                this.tbHtmlRegex.Text = this.lvResult.SelectedItems[0].SubItems[7].Text;
                this.tbSnapRegex.Text = this.lvResult.SelectedItems[0].SubItems[8].Text;
                this.tbPageRegex.Text = this.lvResult.SelectedItems[0].SubItems[9].Text;
                this.tbCountRegex.Text = this.lvResult.SelectedItems[0].SubItems[10].Text;

                this.gbtnSave.Tag = this.lvResult.SelectedItems[0].Tag.ToString();
                this.tsslMsg.Text = "修改模式";
            }
        }

        #endregion

        #region Label

        private void lblClose_Click(object sender, EventArgs e)
        {
            this.pInfo.Visible = false;
        }

        #endregion

        #region PictureBox

        private void pbURL_Click(object sender, EventArgs e)
        {
            this.lblTitle.Text = "URL格式";
            this.lblComment.Text = "\t搜索引擎搜索页面的url格式，变量只能包含搜索关键字。例如：http://www.baidu.com/s?wd={keywords}";
            this.pInfo.Location = new Point(this.pbURL.Location.X + this.pbURL.Width, this.pbURL.Location.Y + this.pbURL.Height);
            this.pInfo.Visible = true;
            this.pInfo.BringToFront();
        }

        private void pbResultRegex_Click(object sender, EventArgs e)
        {
            this.lblTitle.Text = "信息采集正则";
            this.lblComment.Text = "\t用于采集搜索结果，需要包含变量有url（网址）、title（标题）、date（快照日期）、snapshot（快照地址）。例如：data-click(.*?)href=\"(?<url>(.*?))\"target=\"_blank\">(?<title>(.*?))</a></h3>(.*?)(?<date>(([\\d]{4}-[\\d]{1,2}-[\\d]{1,2})|([\\d]{1,2}小时前)))</span>(.*?)href=\\\"(?<snapshot>(.*?))\\\"target=\\\"";
            this.pInfo.Location = new Point(this.pbResultRegex.Location.X + this.pbResultRegex.Width, this.pbResultRegex.Location.Y + this.pbResultRegex.Height);
            this.pInfo.Visible = true;
            this.pInfo.BringToFront();
        }

        private void pbSectionRegex_Click(object sender, EventArgs e)
        {
            this.lblTitle.Text = "信息采集正则";
            this.lblComment.Text = "\t用于采集搜索结果，需要包含变量有url（网址）、title（标题）、date（快照日期）、snapshot（快照地址）。例如：data-click(.*?)href=\"(?<url>(.*?))\"target=\"_blank\">(?<title>(.*?))</a></h3>(.*?)(?<date>(([\\d]{4}-[\\d]{1,2}-[\\d]{1,2})|([\\d]{1,2}小时前)))</span>(.*?)href=\\\"(?<snapshot>(.*?))\\\"target=\\\"";
            Point p = new Point(this.pbSectionRegex.Location.X + this.pbSectionRegex.Width, this.pbSectionRegex.Location.Y + this.pbSectionRegex.Height);
            if ((p.X + pInfo.Width) > this.ClientSize.Width) p = new Point(this.pbSectionRegex.Location.X - this.pInfo.Width, p.Y);
            this.pInfo.Location = p;
            this.pInfo.Visible = true;
            this.pInfo.BringToFront();
        }

        private void pbHtmlRegex_Click(object sender, EventArgs e)
        {
            this.lblTitle.Text = "信息采集正则";
            this.lblComment.Text = "\t用于采集搜索结果，需要包含变量有url（网址）、title（标题）、date（快照日期）、snapshot（快照地址）。例如：data-click(.*?)href=\"(?<url>(.*?))\"target=\"_blank\">(?<title>(.*?))</a></h3>(.*?)(?<date>(([\\d]{4}-[\\d]{1,2}-[\\d]{1,2})|([\\d]{1,2}小时前)))</span>(.*?)href=\\\"(?<snapshot>(.*?))\\\"target=\\\"";
            this.pInfo.Location = new Point(this.pbHtmlRegex.Location.X + this.pbHtmlRegex.Width, this.pbHtmlRegex.Location.Y + this.pbHtmlRegex.Height);
            this.pInfo.Visible = true;
            this.pInfo.BringToFront();
        }

        private void pbSnapRegex_Click(object sender, EventArgs e)
        {
            this.lblTitle.Text = "信息采集正则";
            this.lblComment.Text = "\t用于采集搜索结果，需要包含变量有url（网址）、title（标题）、date（快照日期）、snapshot（快照地址）。例如：data-click(.*?)href=\"(?<url>(.*?))\"target=\"_blank\">(?<title>(.*?))</a></h3>(.*?)(?<date>(([\\d]{4}-[\\d]{1,2}-[\\d]{1,2})|([\\d]{1,2}小时前)))</span>(.*?)href=\\\"(?<snapshot>(.*?))\\\"target=\\\"";
            this.pInfo.Location = new Point(this.pbSnapRegex.Location.X + this.pbSnapRegex.Width, this.pbSnapRegex.Location.Y + this.pbSnapRegex.Height);
            this.pInfo.Visible = true;
            this.pInfo.BringToFront();
        }

        private void pbPageRegex_Click(object sender, EventArgs e)
        {
            this.lblTitle.Text = "页码采集正则";
            this.lblComment.Text = "\t用于采集搜索结果页面的下一页链接。例如：href=\\\"(?<url>(.*?))\\\">下一页&gt;</a>";
            this.pInfo.Location = new Point(this.pbPageRegex.Location.X + this.pbPageRegex.Width, this.pbPageRegex.Location.Y + this.pbPageRegex.Height);
            this.pInfo.Visible = true;
            this.pInfo.BringToFront();
        }

        #endregion

        #endregion

        #region Method

        private void InitComboBox()
        {
            ArrayList List = new ArrayList();
            List.Add(new DictionaryEntry("936", "简体中文 (GB2312)"));
            List.Add(new DictionaryEntry("950", "繁体中文 (Big5)"));
            List.Add(new DictionaryEntry("65001", "Unicode (UTF-8)"));
            List.Add(new DictionaryEntry("20936", "简体中文 (GB2312-80)"));
            List.Add(new DictionaryEntry("50227", "简体中文 (ISO-2022)"));
            List.Add(new DictionaryEntry("52936", "简体中文 (HZ)"));
            List.Add(new DictionaryEntry("54936", "简体中文 (GB18030)"));

            this.cbbCodeName.DisplayMember = "Value";
            this.cbbCodeName.ValueMember = "Key";
            this.cbbCodeName.DataSource = List;
            this.cbbCodeName.SelectedIndex = 0;
        }

        private void LoadData()
        {
            DataTable dt = QT.SEO.SearchEngine.GetAll();
            int i=1;
            this.lvResult.Items.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                ListViewItem item = new ListViewItem();
                item.SubItems[0].Text = i.ToString();
                item.SubItems.Add(dr["SearchName"].ToString());
                item.SubItems.Add(dr["URI"].ToString());
                item.SubItems.Add(dr["CodePage"].ToString());
                item.SubItems.Add(dr["CodeName"].ToString());
                item.SubItems.Add(dr["ResultRegex"].ToString());
                item.SubItems.Add(dr["SectionRegex"].ToString());
                item.SubItems.Add(dr["HtmlRegex"].ToString());
                item.SubItems.Add(dr["SnapRegex"].ToString());
                item.SubItems.Add(dr["PageRegex"].ToString());
                item.SubItems.Add(dr["CountRegex"].ToString());
                item.Tag = dr["sid"].ToString();
                this.lvResult.Items.Add(item);
                i++;
            }
            this.lvResult.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        }

        #endregion
    }
}
